//
//  GradientDotSpinnerView.swift
//  STest
//
//  Created by wang tiao on 2025/9/13.
//

import UIKit

class GradientDotSpinnerView: UIView {

    /// 点的数量
    var dotCount: Int = 12
    
    /// 圆环半径
    var radius: CGFloat = 40
    
    /// 点的大小
    var dotSize: CGFloat = 8
    
    /// 渐变颜色数组
    var gradientColors: [UIColor] = [.red, .orange, .yellow, .green, .blue, .purple]
    
    private var dotLayers: [CAShapeLayer] = []
    private let containerLayer = CALayer()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setup()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setup()
    }
    
    private func setup() {
        backgroundColor = .clear
        layer.addSublayer(containerLayer)
        setupDots()
    }
    
    private func setupDots() {
        containerLayer.sublayers?.forEach { $0.removeFromSuperlayer() }
        dotLayers.removeAll()
        
        for i in 0..<dotCount {
            let dot = CAShapeLayer()
            
            // 渐变颜色分布
            let colorIndex = i * gradientColors.count / dotCount
            dot.fillColor = gradientColors[colorIndex % gradientColors.count].cgColor
            
            dot.path = UIBezierPath(ovalIn: CGRect(x: -dotSize/2, y: -dotSize/2, width: dotSize, height: dotSize)).cgPath
            
            // 角度
            let angle = CGFloat(i) / CGFloat(dotCount) * 2 * .pi
            let x = bounds.midX + radius * cos(angle)
            let y = bounds.midY + radius * sin(angle)
            dot.position = CGPoint(x: x, y: y)
            
            containerLayer.addSublayer(dot)
            dotLayers.append(dot)
            
            // 缩放动画
            let scaleAnim = CABasicAnimation(keyPath: "transform.scale")
            scaleAnim.fromValue = 0.3
            scaleAnim.toValue = 1.0
            scaleAnim.duration = 0.6
            scaleAnim.autoreverses = true
            scaleAnim.repeatCount = .infinity
            scaleAnim.beginTime = CACurrentMediaTime() + Double(i) * 0.05 // 错开动画
            dot.add(scaleAnim, forKey: "scale")
        }
    }
    
    /// 开始旋转
    func startAnimating(rotationDuration: CFTimeInterval = 1.5) {
        stopAnimating()
        let rotate = CABasicAnimation(keyPath: "transform.rotation")
        rotate.fromValue = 0
        rotate.toValue = 2 * CGFloat.pi
        rotate.duration = rotationDuration
        rotate.repeatCount = .infinity
        containerLayer.add(rotate, forKey: "rotation")
    }
    
    /// 停止旋转
    func stopAnimating() {
        containerLayer.removeAnimation(forKey: "rotation")
        dotLayers.forEach { $0.removeAnimation(forKey: "scale") }
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        containerLayer.frame = bounds
        setupDots()
    }
}
